package com.atomone.epublib.presenter;


import android.graphics.Bitmap;

import com.atomone.epublib.contract.ReadContract;
import com.atomone.epublib.model.CollBookBean;
import com.atomone.epublib.model.EpubChapter;
import com.atomone.epublib.utils.EpubUtils;
import com.atomone.epublib.utils.LogUtils;
import com.atomone.epublib.utils.MD5Utils;
import com.atomone.epublib.utils.RxUtils;
import com.orhanobut.logger.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.epub.EpubReader;
import nl.siegmann.epublib.service.MediatypeService;


/**
 * @author liyayun
 */
public class ReadPresenter implements ReadContract.Presenter {

    private static final String TAG = "ReadPresenter";

    private CompositeDisposable mDisposable;

    private ReadContract.View mView;

    @Override
    public void attachView(ReadContract.View view) {
        this.mView = view;
        this.mDisposable = new CompositeDisposable();
    }

    @Override
    public void detachView() {
        mDisposable.clear();
    }

    @Override
    public void loadBook(String bookPath) {
        File bookFile = new File(bookPath);

        Disposable disposable = Observable.just(bookFile)
                .map(file -> {
                    // read epub file
                    EpubReader epubReader = new EpubReader();
                    // import
                    Book book = epubReader.readEpubLazy(bookFile.getAbsolutePath(), "UTF-8", Arrays.asList(MediatypeService.mediatypes));
                    //
                    CollBookBean bookBean = new CollBookBean(book);
                    return bookBean;
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(bookBean -> {

                    Book book = bookBean.getBook();
                    // 封面不为空
                    Bitmap bitmap = null;
                    if (book.getCoverImage() != null) {
                        byte[] image = book.getCoverImage().getData();
                        bitmap = EpubUtils.resizeImage(image);
                        book.getCoverImage().close();
                    }
                    //
                    mView.showBookInfo(bookBean, bitmap);
                    // 封面数据
                    Resource resource = book.getCoverPage();
                    StringBuilder builder = new StringBuilder();
                    try {
                        BufferedReader r = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                        String aux = "";
                        while ((aux = r.readLine()) != null) {
                            builder.append(aux);
                        }
                        Logger.d("cover " + r.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }, Throwable::printStackTrace);

        mDisposable.add(disposable);
    }


//    @Override
//    public void loadCategory() {
//
//                Disposable disposable = RemoteRepository.getInstance()
//                        .getBookChapters(bookId)
//                        .doOnSuccess(new Consumer<List<BookChapterBean>>() {
//                            @Override
//                            public void accept(List<BookChapterBean> bookChapterBeen) throws Exception {
//                                //进行设定BookChapter所属的书的id。
//                                for (BookChapterBean bookChapter : bookChapterBeen) {
//                                    bookChapter.setId(MD5Utils.strToMd5By16(bookChapter.getLink()));
//                                    bookChapter.setBookId(bookId);
//                                }
//                            }
//                        })
//                        .compose(RxUtils::toSimpleSingle)
//                        .subscribe(
//                                beans -> {
//                                    mView.showCategory(beans);
//                                }
//                                ,
//                                e -> {
//                                    //TODO: Haven't grate conversation method.
//                                    LogUtils.e(e.get);
//                                }
//                        );
//                addDisposable(disposable);
//    }

    @Override
    public void loadChapter(List<EpubChapter> bookChapters) {
        //        int size = bookChapters.size();
        //
        //        //取消上次的任务，防止多次加载
        //        if (mChapterSub != null) {
        //            mChapterSub.cancel();
        //        }
        //
        //        List<Single<ChapterInfoBean>> chapterInfos = new ArrayList<>(bookChapters.size());
        //        ArrayDeque<String> titles = new ArrayDeque<>(bookChapters.size());
        //
        //        // 将要下载章节，转换成网络请求。
        //        for (int i = 0; i < size; ++i) {
        //            TxtChapter bookChapter = bookChapters.get(i);
        //            // 网络中获取数据
        //            Single<ChapterInfoBean> chapterInfoSingle = RemoteRepository.getInstance()
        //                    .getChapterInfo(bookChapter.getLink());
        //
        //            chapterInfos.add(chapterInfoSingle);
        //
        //            titles.add(bookChapter.getTitle());
        //        }
        //
        //        Single.concat(chapterInfos)
        //                .subscribeOn(Schedulers.io())
        //                .observeOn(AndroidSchedulers.mainThread())
        //                .subscribe(
        //                        new Subscriber<ChapterInfoBean>() {
        //                            String title = titles.poll();
        //
        //                            @Override
        //                            public void onSubscribe(Subscription s) {
        //                                s.request(Integer.MAX_VALUE);
        //                                mChapterSub = s;
        //                            }
        //
        //                            @Override
        //                            public void onNext(ChapterInfoBean chapterInfoBean) {
        //                                //存储数据
        //                                BookRepository.getInstance().saveChapterInfo(
        //                                        bookId, title, chapterInfoBean.getBody()
        //                                );
        //                                mView.finishChapter();
        //                                //将获取到的数据进行存储
        //                                title = titles.poll();
        //                            }
        //
        //                            @Override
        //                            public void onError(Throwable t) {
        //                                //只有第一个加载失败才会调用errorChapter
        //                                if (bookChapters.get(0).getTitle().equals(title)) {
        //                                    mView.errorChapter();
        //                                }
        //                                LogUtils.e(t);
        //                            }
        //
        //                            @Override
        //                            public void onComplete() {
        //                            }
        //                        }
        //                );
    }


}
